//
//  FileManager+CoreKit.swift
//  OMTCoreKitSwift
//
//  Created by 昭荣伊 on 2018/12/7.
//

import Foundation

extension FileManager {
    /// 文档目录
    public static var documentPath: String = {
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let path: String! = paths.first
        return path
    }()
    
    /// 偏好设置目录
    public static var preferencesPath: String = {
        var path = FileManager.libraryDirectory
        path.append(contentsOf: "/Preferences")
        FileManager.mkdir(atPath: path)
        return path
    }()
    
    /// 缓存目录
    public static var cachePath: String = {
        var path = FileManager.libraryDirectory
        path.append(contentsOf: "/Caches")
        FileManager.mkdir(atPath: path)
        return path
    }()
    
    /// 临时文件目录
    public static var tmpPath: String = {
        var path = FileManager.libraryDirectory
        path.append(contentsOf: "/tmp")
        FileManager.mkdir(atPath: path)
        return path
    }()
    
    
    /// 创建目录
    ///
    /// - Parameter path: 目录路径
    /// - Returns: true 成功 false 失败
    @discardableResult
    public static func mkdir(atPath path: String) -> Bool {
        if (!FileManager.default.fileExists(atPath: path)) {
            do {
                try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                return false
            }
        }
        return true
    }
    
    /// 创建文件
    ///
    /// - Parameter filePath: 文件路径
    /// - Returns: true 成功 false 失败
    @discardableResult
    public static func touchFile(atPath filePath: String) -> Bool {
        if (!FileManager.default.fileExists(atPath: filePath)) {
            FileManager.default.createFile(atPath: filePath, contents: nil, attributes: nil)
        }
        return true
    }
    
    /// libraryDirectory
    private static var libraryDirectory: String = {
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let path: String! = paths.first
        return path
    }()
}
